import type Node from 'element-plus/es/components/tree/src/model/node';

interface Tree {
  label: string;
  value: string;
  leaf: boolean;
  level: number;
}

export interface TreeDataProp {
  selectValue: string;
  selectLabel: string;
  selectId: number;
  data: any[];
}

export function useTreeData() {
  let treeData = ref<TreeDataProp>({
    selectValue: '',
    selectLabel: '',
    selectId: null,
    data: []
  });

  /**
   * 清空树形数据
   */
  const clearTreeData = () => {
    Object.assign(treeData.value, {
      selectValue: '',
      selectLabel: '',
      selectId: null
    });
  };
  /**
   * 选择树形数据
   */
  const selectTreeData = row => {
    const { label, id, dicCode } = row || {};
    Object.assign(treeData.value, {
      selectValue: dicCode,
      selectLabel: label,
      selectId: id
    });
  };

  onBeforeMount(() => {
    searchTreeData();
  });
  const searchTreeData = () => {
    dictCatalogTree().then(data => {
      if (data) {
        let tData = [];
        Object.keys(data).forEach((key, index) => {
          const children = data[key] || [];
          let item = {
            label: key,
            id: index,
            level: 1,
            children: children.map(son => {
              return {
                label: son.dicMark,
                id: son.id,
                dicCode: son.dicCode,
                level: 2
              };
            })
          };
          tData.push(item);
        });
        treeData.value.data = tData;
      }
    });
  };

  /**根据code查询pid */
  const findPidByCode = (code: string): number => {
    for (let item of treeData.value.data) {
      for (let son of item.children) {
        if (son.dicCode == code) {
          return item.id;
        }
      }
    }
  };

  return {
    treeData,
    searchTreeData,
    clearTreeData,
    selectTreeData,
    findPidByCode
  };
}
